package paskal.ui.components;

import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.util.Map;

import javax.swing.JPanel;

import paskal.ui.Style;

public class Panel extends JPanel implements Component {
	private static final long serialVersionUID = 6934751114154409997L;

	private BufferedImage backgroundImage;
	private GradientPaint gradient = null;

	public Panel() {
	}

	@Override
	public void stylize(String selector) {
		Style.getInstance().styleThisShit(selector, this);
	}

	@Override
	public void setProperty(String key, Object value) {
		switch (key) {
		case "bounds": {
			setBounds((Rectangle) value);
			break;
		}
		case "background": {
			@SuppressWarnings("unchecked")
			Map<String, Object> background = (Map<String, Object>) value;

			@SuppressWarnings("unchecked")
			Map<String, Object> gradient = (Map<String, Object>) background
					.get("gradient");
			if (gradient != null) {
				Color c2 = new Color(Integer.parseInt(gradient.get("endColor")
						.toString().substring(1), 16));
				Color c1 = new Color(Integer.parseInt(gradient
						.get("startColor").toString().substring(1), 16));
				Point p1 = (Point) gradient.get("startPoint");
				Point p2 = (Point) gradient.get("endPoint");
				this.gradient = new GradientPaint(p1.x, p1.y, c1, p2.x, p2.y,
						c2);
			}

			String path = (String) background.get("image");
			if (path != null) {
				Point p = (Point) background.get("position");
				if (p != null) {
					Rectangle r = new Rectangle(p);
					r.height = getHeight();
					r.width = getWidth();
					backgroundImage = Style.getInstance().getImage(path, r);
				} else {
					backgroundImage = Style.getInstance().getImage(path);
				}
			}
			break;
		}
		default:
			break;
		}
	}

	@Override
	protected void paintComponent(Graphics g) {
		if (backgroundImage != null) {
			g.drawImage(backgroundImage, 0, 0, null);
		} else if (gradient != null) {
			Graphics2D g2 = (Graphics2D) g;
			g2.setPaint(gradient);
			g2.fillRect(0, 0, getWidth(), getHeight());
		} else {
			super.paintComponent(g);
		}
	}
}
